const fs = require('fs');
const path = require('path');
const { versionCore } = require('../src/version-core');

// 智能版本链接器
class VersionLinker {
  constructor() {
    this.baseDir = path.join(__dirname, '..');
    this.versionLayers = {
      core: ['v1', 'v2'],
      adapters: ['v1', 'v2'],
      platform: ['v1', 'v2'],
      wasm: ['v1']
    };
  }

  // 创建智能符号链接
  async createSmartSymlinks() {
    await this.createVersionLinks();
    this.createCoreLinks();
  }

  // 创建版本链接
  async createVersionLinks() {
    for (const [module, versions] of Object.entries(this.versionLayers)) {
      for (const version of versions) {
        await this.createModuleVersionLink(module, version);
      }
    }
  }

  // 创建模块版本链接
  async createModuleVersionLink(module, version) {
    const srcDir = path.join(this.baseDir, 'src', module, version);
    const distDir = path.join(this.baseDir, 'dist', module, version);

    // 确保目录存在
    await fs.promises.mkdir(srcDir, { recursive: true });
    await fs.promises.mkdir(distDir, { recursive: true });

    // 创建版本链接
    const versionLinkPath = path.join(this.baseDir, 'node_modules', `@${module}`, version);
    await this.forceSymlink(srcDir, versionLinkPath);
    
    console.log(`Created version link: ${versionLinkPath} -> ${srcDir}`);
  }

  // 创建核心链接(指向最新兼容版本)
  createCoreLinks() {
    for (const module of Object.keys(this.versionLayers)) {
      const coreVersion = versionCore.getCompatibleVersion(module);
      const coreLinkPath = path.join(this.baseDir, 'node_modules', `@${module}`);
      
      this.forceSymlink(
        path.join(this.baseDir, 'src', module, coreVersion),
        coreLinkPath
      );
      
      console.log(`Created core link: ${coreLinkPath} -> ${path.join('src', module, coreVersion)}`);
    }
  }

  // 强制创建符号链接(存在则替换)
  async forceSymlink(target, linkPath) {
    try {
      await fs.promises.unlink(linkPath);
    } catch (err) {
      if (err.code !== 'ENOENT') throw err;
    }
    await fs.promises.symlink(
      path.relative(path.dirname(linkPath), target),
      linkPath,
      'dir'
    );
  }
}

// 执行链接创建
new VersionLinker().createSmartSymlinks().catch(console.error);